#include "iic_basen32lib.h"
#include "AHT10.h"
#include <stdio.h>

s_iic_bus_t AHT_bus =
{
	.IIC_SDA_GPIO = AHT10_SDA_GPIO,
	.IIC_SCL_GPIO = AHT10_SCL_GPIO,
	.IIC_SDA_PIN  = AHT10_SDA_PIN,
	.IIC_SCL_PIN  = AHT10_SCL_PIN,
};
/**
  * @brief aht10的SCL与SDA时钟使能
  * @param None
  * @retval None
  */
static void aht10_clk_en(void)
{
		aht10_scl_clk_en();
		aht10_sda_clk_en();
}
/**
brief AHT10初始化函数
param NONE
return NONE
*/
void AHT10Init()
{
	u8 ack=0;
	aht10_clk_en();
	IICInit(&AHT_bus);
	delay_ms(100);

	IICStart(&AHT_bus);
	IICSendByte(&AHT_bus, AHT10_ADDRESS);
	ack=IICWaitAck(&AHT_bus);//printf("ack is %d\r\n",ack);
	IICSendByte(&AHT_bus,0xe1);
	ack=IICWaitAck(&AHT_bus);//printf("ack is %d\r\n",ack);
	IICSendByte(&AHT_bus,0x00);
	ack=IICWaitAck(&AHT_bus);//printf("ack is %d\r\n",ack);
	IICSendByte(&AHT_bus,0x00);
	IICStop(&AHT_bus);
	delay_ms(40);//延时40ms让传感器稳定
}

/**
brief 检查AHT10是否存在
param NONE
return 0存在  1不存在
*/
u8 AHT10Check(void)
{
	u8 ack=0;
	IICStart(&AHT_bus);
	IICSendByte(&AHT_bus, AHT10_ADDRESS );
	ack=IICWaitAck(&AHT_bus);
	IICStop(&AHT_bus);
	return ack;
}

/**
brief AHT10软复位
param NONE
return NONE
*/
void AHT10Reset(void)
{
	IICStart(&AHT_bus);
	IICSendByte(&AHT_bus, AHT10_WRITE);
	IICWaitAck(&AHT_bus);
	IICSendByte(&AHT_bus, 0xba);
	IICWaitAck(&AHT_bus);
	IICStop(&AHT_bus);
}

/**
brief 检查AHT10读温湿度数据
param *temperature：需要读出的温度数据，float指针类型,精度范围+-0.3C
param *humidity：需要读出的湿度数据，u8指针类型,精度范围+-2RH
return 0 读数据正常 1读数据失败
*/
u8 AHT10ReadData(float *temperature,u8 *humidity)
{
	u8 ack;
	u32 SRH=0,ST=0;
	u8 databuff[6];
	IICStart(&AHT_bus);
	IICSendByte(&AHT_bus,AHT10_WRITE);
	ack = IICWaitAck(&AHT_bus);//printf("ack is %d\r\n",ack);
	IICSendByte(&AHT_bus, 0xac);
	ack = IICWaitAck(&AHT_bus);//printf("ack is %d\r\n",ack);
	IICSendByte(&AHT_bus,0x33);
	ack = IICWaitAck(&AHT_bus);//printf("ack is %d\r\n",ack);
	IICSendByte(&AHT_bus,0x00);
	ack = IICWaitAck(&AHT_bus);//printf("ack is %d\r\n",ack);
	IICStop(&AHT_bus);
	delay_ms(80);//延时一会等待数据读出
	IICStart(&AHT_bus);
	IICSendByte(&AHT_bus,AHT10_READ);
	ack = IICWaitAck(&AHT_bus);//printf("ack is %d\r\n",ack);
	ack=IICReceiveByte(&AHT_bus,1);//printf("ack is %d\r\n",ack);
	if((ack&0x40)==0)
	{
		databuff[0]=IICReceiveByte(&AHT_bus,1);
		databuff[1]=IICReceiveByte(&AHT_bus,1);
		databuff[2]=IICReceiveByte(&AHT_bus,1);
		databuff[3]=IICReceiveByte(&AHT_bus,1);
		databuff[4]=IICReceiveByte(&AHT_bus,0);
		//printf("buff is %d %d %d %d %d\r\n",databuff[0],databuff[1],databuff[2],databuff[3],databuff[4]);
		IICStop(&AHT_bus);
		SRH=(databuff[0]<<12)+(databuff[1]<<4)+(databuff[2]>>4);
		ST=((databuff[2]&0X0f)<<16)+(databuff[3]<<8)+(databuff[4]);
		*humidity=(int)(SRH*100.0/1024/1024+0.5);
		*temperature=((int)(ST*2000.0/1024/1024+0.5))/10.0-50;
		return 0;
	}
	IICStop(&AHT_bus);
	return 1;
}




